<?php

namespace app\admin\controller\test;

use app\common\controller\Backend;
use app\admin\model\test\Itembank;
use app\admin\model\test\Testitem;
use app\admin\model\test\Testuser;
use think\Db;
use Exception;
use \think\exception\PDOException;
use think\Session;

/**
 * 试卷管理
 *
 * @icon fa fa-circle-o
 */
class Test extends Backend
{
    
    /**
     * Test模型对象
     * @var \app\admin\model\test\Test
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\test\Test;
        $this->view->assign("statusList", $this->model->getStatusList());

        $this->user = Session::get("admin");
        $this->assign("user",$this->user);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 应急管理局 可以看所有试卷 ，企业可看自家试卷+应急管理局的试卷
            if ($this->user['merchant_id'] == $this->yjMerchantId) { // 应急管理局
                $total = $this->model
                ->with(['article','merchant'])
                ->where($where)
                ->count();

                $list = $this->model
                ->with(['article','merchant'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            } else{ // 企业登录
                    $total = $this->model
                    ->with(['article','merchant'])
                    ->where($where)
                    ->where('test.merchant_id','in',[$this->yjMerchantId,$this->user['merchant_id']])
                    ->count();
    
                    $list = $this->model
                    ->with(['article','merchant'])
                    ->where($where)
                    ->where('test.merchant_id','in',[$this->yjMerchantId,$this->user['merchant_id']])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

	
	/**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					//获取是否有人答题
					$total_user = Testuser::where(['test_id'=>$v['id']])->count();
					if($total_user < 1){
						$count += $v->delete();
						//删除对应试卷试题
						Testitem::where(['test_id'=>$v['id']])->delete();
					}
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count){
                $this->success('成功删除'.$count.'个试卷，失败'.(count($list)-$count).'个，原因:已有用户答题某试卷！');
            } else {
                $this->error(__('No rows were deleted').' 可能原因:已有用户答题某试卷，不允许删除');
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

	/**
     * 预览
     */
    public function preview($ids = null)
    {
		$row = $this->model->get($ids);
		 if (!$row) {
            $this->error(__('No Results were found'));
        }
		$itemList = Testitem::with(['itembank'])->where(['test_id'=>$row['id']])->order('weigh DESC')->select();
		foreach ($itemList as $val) {
            $val->visible(['id','weigh','number','score']);
            $val->visible(['itembank']);
			$val->getRelation('itembank')->visible(['title','content','video','type','values','answer','answer_key']);
        }
		//var_dump($itemList);die;
		$this->view->assign("row", $row);
		$this->view->assign("itemList", $itemList);
	
        return $this->view->fetch();
    }

}
